package com.ghyf.mplay.service;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.format.Time;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;

import com.ghyf.mplay.application.CookieConstants;
import com.ghyf.mplay.application.UserInfoSingleton;
import com.ghyf.mplay.bean.BaseModuleInfo;

import com.ghyf.mplay.bean.LayoutInfo;
import com.ghyf.mplay.bean.PlaylistInfo;

import com.ghyf.mplay.datatype.LayoutItem;
import com.ghyf.mplay.datatype.ModuleItem;

import com.ghyf.mplay.engine.XmlParser;
import com.ghyf.mplay.engineImpl.XmlparserImpl;
import com.ghyf.mplay.net.common.RecvBase;
import com.ghyf.mplay.net.data.PriorityTextData;
import com.ghyf.mplay.net.log.LogTool;
import com.ghyf.mplay.uimanager.ViewManager;
import com.ghyf.mplay.util.CommonUtil;
import com.ghyf.mplay.util.LogUtil;
import com.ghyf.mplay.util.VeDate;

import com.ghyf.mplay.value.ConstantValue;
import com.ghyf.mplay.view.MExigent;


/**
 * 负责判断当该解析哪个布局文件，为界面显示提供数据的服务
 * @author 陈小红
 *
 */
@SuppressLint("HandlerLeak")
public class ScheduleService extends Service {
	
	private static final String TAG="ScheduleService";
	
	private ViewGroup viewGroup;
	private ArrayList<BaseModuleInfo> moduleInfoList; // 模块数组集合
	private PlaylistInfo playlistInfo; // 播表文件信息
	private ArrayList<LayoutItem> layout_list; // 模板数组集合
	private LayoutItem current_layout_item;
	private LayoutItem next_item;
	private ListIterator<LayoutItem> iterator;
	private String layout_name;
	private String layout_dir;
	private String layout_path;
	private String playlist_dir;
	private XmlParser parser;
	private LayoutInfo layoutInfo = null; // 模板信息
	private boolean isChangeView=false;
	/**是否紧急消息*/
	private boolean isExigent=false;
	private Thread changeViewThread=null;
	private Drawable bk_drawable;
	
	
	/**当前显示紧急消息ID */
	private String currTextId="";
	
	private PriorityTextData currPriorityData=null;
	/**
	 * 紧急消息集合
	 */
	private ArrayList<PriorityTextData> currPriorityDatas=new ArrayList<PriorityTextData>(); // 紧急消息集合;
	
	private AudioManager mAudioManager;
	
	private int max;
	/**当前音量***/
	private int current=0;
	@Override
	public void onCreate() {

		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(RecvBase.ACTION_CMD_CONTROL);
		//注册广播      
		registerReceiver(serviceReceiver, myIntentFilter);
		//获取音频服务 通过mAudioManager可以调整音量和静音设置
		mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		super.onCreate();
	}
	

	
	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		init();

	}
	
	@Override
	public void onDestroy() {
		closeViewThread();
		//取消注册广播     
		unregisterReceiver(serviceReceiver);
		
		super.onDestroy();
	}
	

	//  实际的路径需读取配置文件获得。
	public void init(){
		
		try {
			playLocal();
		} catch (Exception e) {
			LogUtil.e(TAG,"解析playlist出错 ", e);
			
		}
	
	}
	public void down(){
		
		try {
			playDown();
		} catch (Exception e) {
			LogUtil.e(TAG,"解析playlist出错 ", e);
			int myPid = android.os.Process.myPid();
			
			android.os.Process.killProcess(myPid); // 没有文件则停止该应用程序。
		}
	
	}
	public void setPlayList(){
		
		try {
			String[] ss=playlist_dir.split("/");
			RecvBase.playList=ss[ss.length-1];
			
		} catch (Exception e) {
			LogUtil.e(TAG,"解析playlist出错 ", e);
		
		}
		
	}
	/**
	 * 播放模板
	 * 2013-12-4 下午8:16:31
	 *
	 */
	public void playLocal(){
	try {
			/**
			 * 默认处于非紧急状态！~~~~
			 */
			isExigent=false;
			UserInfoSingleton.putIntAndCommit(CookieConstants.EmergStatus, ConstantValue.EMERGSTATUS_NO);
			UserInfoSingleton.putIntAndCommit(CookieConstants.VideoStatus, ConstantValue.VIDEOSTATUS_YES);
			playlist_dir=UserInfoSingleton.getPlayPath();
			setPlayList();
//			String playlist_path = playlist_dir + "playlist.xml"; // 当前播表文件路径
			parser = new XmlparserImpl();
			playlistInfo = parser.parsePlaylist(playlist_dir);
			LogUtil.i(TAG, "根据路径解析成功");
			layout_list = playlistInfo.getLayout_list();
			if(layout_list==null)return;
			if(layout_list.size()==0)return;
			iterator = layout_list.listIterator();

			// init800x480();
			// init1280x720();
			// init1280x720_show();
			// 如果有下个元素
			while (iterator.hasNext()) {
				// 获取第一个模板项
				LayoutItem item = iterator.next();
				// 获取当前时间毫秒值
				long currentTimeMillis = System.currentTimeMillis();
				Time current_time = new Time();
				current_time.set(currentTimeMillis);
				Time start_time = item.getStart_time(); // 开始时间
				if (timeToMillis(current_time) >= timeToMillis(start_time)) { // 如果当前时间晚于或等于本模板开始播放时间
					current_layout_item = item;
					break; // 找到后退出循环
				}
			}
			if (current_layout_item == null) { // 如果一个都没找到，则播放第一个
				while (iterator.hasPrevious()) {
					iterator.previous();
				}
				current_layout_item = iterator.next();
			}
			
			findNext();//找到下一个layout
			
			initCurrentLayout();

			ViewManager.getInstance().changeContentView(viewGroup, moduleInfoList); // 更改界面
			
			// 开启界面显示切换的线程。
			isChangeView=true;
			if(changeViewThread==null){
				changeViewThread=new ChangeViewThread();
			}
			changeViewThread.start();

		}catch (Exception e) {
			
			LogUtil.e(TAG,"取数据出错 ", e);
		
		}
	}
	/**
	 * 播放下载的播表<br>
	 * 2014-11-28 上午10:00:15
	 *
	 */
	public void playDown(){
		try {
				isExigent=false;
				playlist_dir=UserInfoSingleton.getPlayPath();
				setPlayList();
//				String playlist_path = playlist_dir + "PLAYLIST.XML"; // 当前播表文件路径
				parser = new XmlparserImpl();
				playlistInfo = parser.parsePlaylist(playlist_dir);
				LogUtil.i(TAG, "根据路径解析成功");
				layout_list = playlistInfo.getLayout_list();
				if(layout_list==null){
					return;
				}
				if(layout_list.size()==0){
					return;
				}
				iterator = layout_list.listIterator();

				// init800x480();
				// init1280x720();
				// init1280x720_show();
				// 如果有下个元素
				while (iterator.hasNext()) {
					// 获取第一个模板项
					LayoutItem item = iterator.next();
					// 获取当前时间毫秒值
					long currentTimeMillis = System.currentTimeMillis();
					Time current_time = new Time();
					current_time.set(currentTimeMillis);
					Time start_time = item.getStart_time(); // 开始时间
					if (timeToMillis(current_time) >= timeToMillis(start_time)) { // 如果当前时间晚于或等于本模板开始播放时间
						current_layout_item = item;
						break; // 找到后退出循环
					}
				}
				if (current_layout_item == null) { // 如果一个都没找到，则播放第一个
					while (iterator.hasPrevious()) {
						iterator.previous();
					}
					current_layout_item = iterator.next();
				}
				
				findNext();//找到下一个layout
				
				initCurrentLayout();
				
				ViewManager.getInstance().changeContentView(viewGroup, moduleInfoList); // 更改界面
				
				// 开启界面显示切换的线程。
				isChangeView=true;
				if(changeViewThread==null){
					changeViewThread=new ChangeViewThread();
				}
			
				changeViewThread.start();

				
			}catch (Exception e) {
				
				LogUtil.e(TAG,"取数据出错 ", e);
			
			}
		}

	Bitmap bk_bitmap =null;
	 
	// 设置背景图片
	String bk_file_path=null;
	int width = 0;
	int height = 0;
	@SuppressWarnings("deprecation")
	void initViewGroup(){
		try{
			viewGroup = new FrameLayout(getApplicationContext()); // 创建控件容器，显示布局
			viewGroup.setLayoutParams(new LayoutParams(width, height)); // 设置容器的宽高
			if(bk_file_path!=null&&!"".equals(bk_file_path)){
//				bk_bitmap=BitmapFactory.decodeFile(bk_file_path);//获取背景图片
				bk_bitmap=CommonUtil.fitSizeImg(bk_file_path);
			     // 加入到软引用
			    SoftReference<Bitmap> mReference = new SoftReference<Bitmap>(bk_bitmap);
			    // 先判断是否已经回收----
			 	if(bk_bitmap != null && !bk_bitmap.isRecycled()){ 
			 			// 回收并且置为null
//			 			bk_bitmap.recycle(); 
			 			// 释放硬应用
			 			bk_bitmap = null; 
			 	} 
			    // 获取软引用中的位图变量
			    Bitmap getBitmap = mReference.get();
			    if(getBitmap != null) {
			        // 软引用的bitmap为null(已被回收)
					bk_drawable = new BitmapDrawable(getBitmap);
					viewGroup.setBackgroundDrawable(bk_drawable);
			    } 

			}
		}catch(Exception e){
			LogUtil.e(TAG, "initViewGroup fund error", e);
		}
	}
	
	/**
	 * 解析并显示当前模板
	 */
	void initCurrentLayout() {
		try{
			if(null==current_layout_item)return;
			if(null==playlist_dir||"".equals(playlist_dir))return;
			layout_name = current_layout_item.getLayout_name();	//当前布局文件的名称
			layout_dir = playlist_dir + layout_name + "/";	
			layout_path = layout_dir ;	//当前布局文件的路径  + "LAYOUT.XML"
			try {
				LogUtil.i(TAG, "layout_path="+layout_path);
				layoutInfo = parser.parseLayout(layout_path);
				if(layoutInfo==null)return;
			} catch (Exception e) {
				LogUtil.e(TAG,"解析layout出错 ", e);
			}
			
			width = layoutInfo.getScreen_width();
			height = layoutInfo.getScreen_height();
			bk_file_path= layoutInfo.getBk_file();	
			
			initViewGroup();
		
			ArrayList<ModuleItem> module_list = layoutInfo.getModule_list();
			ListIterator<ModuleItem> module_list_iterator = module_list
					.listIterator(); // 模块简单信息的数组集合
			moduleInfoList = new ArrayList<BaseModuleInfo>(); // 保存模块信息的数组集合
			LogUtil.i(TAG, "module_list_size:  " + module_list.size());
			
			// 逐一解析模块。
		while (module_list_iterator.hasNext()) {
				ModuleItem moduleItem = module_list_iterator.next();
				String module_name = moduleItem.getName();
				String module_path = layout_dir + module_name + "/" ;
				try {
				
						if(module_path!=null){
							BaseModuleInfo moduleInfo = null;
						
							moduleInfo = parser.parseModule(module_path,module_name);
							moduleInfoList.add(moduleInfo);
						}
					
				} catch (Exception e) {
					LogUtil.e(TAG,"解析" + module_name
							+ ".xml出错 :\n", e);
				}
				
			}
		}catch(Exception e){
			LogUtil.e(TAG, "出现异常", e);
		}finally{
			
			System.gc();
		}
		
		
	}


	
	
	private final Timer timerMail = new Timer();  
	private TimerTask taskMail;  
	private TimerTask taskStopExigent;  
	Handler handlerMail = new Handler() {  
	    @Override 
	    public void handleMessage(Message msg) {  
	      
	        // 要做的事情  
	        try {
	        	switch(msg.what){
	        	case 1:
	        		PriorityTextData data=(PriorityTextData)msg.getData().getSerializable(ConstantValue.EXTRA_OBJ);
		        	startExigent(data);
	        		break;
	        	case 2:
	        		/**
	        		 * 停止前先检查是否还有需要显示  若没有就停止紧急消息（集合是按照级别、结束时间排序）
	        		 * ①、先从紧急消息集合里面迭代 
	        		 * ②、
	        		 */
	        		stopExigent();
	        		
	        		break;
	        
	        	}
	        	
			} catch (Exception e) {
				e.printStackTrace();
			}
	    } 
	};
	
	
	/**
	 * 设置定时的开始时间<br>
	 * 2014-3-3 下午3:33:04
	 * @param startTime
	 *
	 */
	public void setStartTime(final PriorityTextData data){
		try{
			taskMail = new TimerTask() {  
			    @Override 
			    public void run() {  
			        Message message = new Message();  
			        message.what = 1;  
			        Bundle bundle=new Bundle();
			        bundle.putSerializable(ConstantValue.EXTRA_OBJ, data);
			        message.setData(bundle);
			        handlerMail.sendMessage(message);  
			    }  
			};

			Date startDate=VeDate.shortTimeToDate(data.getTextStartTime());
			LogUtil.i(TAG, "start date"+startDate);
			timerMail.schedule(taskMail, startDate);
			
		}catch(Exception e){
			LogUtil.e(TAG, "setStartTime Exception error", e);
		}
	}
	/**
	 * 设置定时的结束时间<br>
	 * 2014-3-3 下午3:33:19
	 * @param stopTime
	 *
	 */
	public void setStopTime(final PriorityTextData data,boolean isCancel){
		try{
			if(isCancel&&taskStopExigent!=null){
				taskStopExigent.cancel();
			}
			
			taskStopExigent= new TimerTask() {  
			    @Override 
			    public void run() {  
			        Message message = new Message();  
			        message.what = 2;  
			        Bundle bundle=new Bundle();
			        bundle.putSerializable(ConstantValue.EXTRA_OBJ, data);
			        message.setData(bundle);
			        handlerMail.sendMessage(message);  
			    }  
			};
			
			Date stopDate=VeDate.shortTimeToDate(data.getTextStopTime());
			LogUtil.i(TAG, "stop date"+stopDate);
			timerMail.schedule(taskStopExigent, stopDate);
			
		}catch(Exception e){
			LogUtil.e(TAG, "setStopTime Exception error", e);
		}
	}
	public void receiveMsg(final PriorityTextData data){
		/**
		 * 暂时这么写 ~~~~~
		 */
		startExigent(data);
		handlerMail.postDelayed(new StartRun(data), 1000);
		handlerMail.postDelayed(new StartRun(data), 2000);
	}
	
	public void mplayStopThread(){
		/**
		 * 暂时这么写 ~~~~~
		 */
		mplayStop();
		handlerMail.postDelayed(new StopThread(), 1000);
		handlerMail.postDelayed(new StopThread(), 2000);
	}
	private class StartRun implements Runnable{
		PriorityTextData data;
		

		private StartRun(PriorityTextData data) {
			super();
			this.data = data;
		}


		/* (non-Javadoc)
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			// TODO Auto-generated method stub
			startExigent(data);
		}
		
	}
	
	private class StopThread implements Runnable{
		private StopThread() {
			super();
		}


		/* (non-Javadoc)
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			mplayStop();
		}
		
	}
	/**
	 * 接收紧急消息<br>
	 * 2014-2-28 上午10:14:45
	 * @param data
	 *
	 */
	public void receiveMsg1(final PriorityTextData data){
		String tempTextId;
		long startTime=data.getTextStartTime();
		long stopTime=data.getTextStopTime();
		/**
		 * 分情况处理
		 * ①、开始时间=0  结束时间=0     判断级别 (1)如果新的相等或小于当前  后面的不做显示。
		 * ②、开始时间=0  结束时间=0     判断级别 (1)如果新的大于当前  直接显示最新的。
		 * ③、开始时间=0 结束时间!=0    判断级别 (1)如果新的小于当前  后面的不做显示。
		 *    (2)如果相等 比较结束时间  如果当前的结束时间为空或比新的结束时间晚 后面不做显示 (3)如果当前结束时间比新的早 在结束时间结束时候显示新的
		 * ④、开始时间=0 结束时间!=0    判断级别 (1)如果新的大于当前  直接显示最新的。
		 * ⑤、开始时间！=0 结束时间!=0    判断级别 (1)如果新的大于当前  直接显示最新的。
		 * ⑥、开始时间！=0 结束时间!=0    判断级别 (1)如果新的小于当前  后面的不做显示。
		 *    (2)如果相等 比较结束时间  如果当前的结束时间为空或比新的结束时间晚 后面不做显示 (3)如果当前结束时间比新的早 在结束时间结束时候显示新的
		 */
		
		/**
		 *判断级别 级别大的先显示
		 */
		tempTextId=currTextId;
		currTextId=data.getTextID();
		if(currPriorityData!=null){
			if(currPriorityData.getTextLevel()<data.getTextLevel()){
				startExigent(data);
				currPriorityData=data;
				if(stopTime!=0){
					setStopTime(data,true);
				}
			}else if(currPriorityData.getTextLevel()==data.getTextLevel()){
				if(stopTime==0)	return;
				Date stopDate=VeDate.shortTimeToDate(stopTime);
				long stopTimeCurr=currPriorityData.getTextStopTime();
				if(stopTimeCurr==0)	return;
				Date stopDateCurr=VeDate.shortTimeToDate(stopTimeCurr);
				if(stopDateCurr.after(stopDate)){
					// 如果当前的结束时间为空或比新的结束时间晚 后面不做显示
					return;
				}else{
					currPriorityDatas.add(data);
				}
				
			}else{
				return;
			}
		}else{
			/**
			 * 第一次进入
			 * startTime =0 马上播放紧急消息
			 */
			if(startTime==0){
				startExigent(data);
				currPriorityData=data;
				
			}else{
				setStartTime(data);
			}
			if(stopTime!=0){
				setStopTime(data,false);
			}
			
		}
	
		
	}
	void mplayPlay(){
		try{
			////开始
			int count=viewGroup.getChildCount();
			for(int i=0;i<count;i++ ){
				View v=viewGroup.getChildAt(i);
				if(v instanceof MExigent){
					v.setVisibility(View.GONE);
				}else{
					v.setVisibility(View.VISIBLE);
				}
			}
			String flag1=UserInfoSingleton.getIslive();
			if(!flag1.equals(ConstantValue.PLAY_LOCAL)){
				ViewManager.getInstance().getlVideo().setVisibility(View.GONE);
				ViewManager.getInstance().getlVideo().stopPlayback();
				ViewManager.getInstance().getSurfaceView().play();
			}
			viewGroup.setBackgroundDrawable(bk_drawable);// 设置模板背景图片
//			sendControlBroadcast(RecvBase.CMD_CONTROL_PLAY,null);
		}catch(Exception e){
			LogUtil.e(TAG,"mplayStop fund error", e);
		}
		
	}
	
	
	void mplayStop(){
		try{
			//// 1111111
			int count=viewGroup.getChildCount();
			for(int i=0;i<count;i++ ){
				View v=viewGroup.getChildAt(i);
				if(v instanceof MExigent){
					v.setVisibility(View.VISIBLE);
				}else{
					v.setVisibility(View.GONE);
				}
			}
			String flag1=UserInfoSingleton.getIslive();
			if(!flag1.equals(ConstantValue.PLAY_LOCAL)){
				ViewManager.getInstance().getSurfaceInfo().closeReceiveThread();
				ViewManager.getInstance().getSurfaceView().pause();
			}
			viewGroup.setBackgroundDrawable(null);// 设置模板背景图片
			viewGroup.setBackgroundColor(Color.argb(255,10,10,10));
			
			closeViewThread();
		}catch(Exception e){
			LogUtil.e(TAG,"mplayStop fund error", e);
		}
	}
	/**
	 * 开始显示紧急模板<br>
	 * 2013-12-4 下午8:01:03
	 *
	 */
	void startExigent(PriorityTextData data){
		
		if(null==ViewManager.getInstance().getExigentInfo())return;
		String module_name = "exigent1";
		try{
			//// 1111111
			int count=viewGroup.getChildCount();
			for(int i=0;i<count;i++ ){
				View v=viewGroup.getChildAt(i);
				if(v instanceof MExigent){
					v.setVisibility(View.VISIBLE);
				}else{
					v.setVisibility(View.GONE);
				}
			}
			String flag1=UserInfoSingleton.getIslive();
			if(flag1.equals(ConstantValue.PLAY_LOCAL)){
				
			}else{
				stopLiveBut();
			}
			
			viewGroup.setBackgroundDrawable(null);// 设置模板背景图片
		    ////22222222222
//			initViewGroup();

//			ViewManager.getInstance().changeExigentContentView(viewGroup, moduleInfoList);
			
			viewGroup.setBackgroundColor(Color.argb(255,10,10,10));
			
			ViewManager.getInstance().getExigentInfo().receiveControlCmd(data);
		
			closeViewThread();
			UserInfoSingleton.setIsExigent("0");
			isExigent=true;
			UserInfoSingleton.putIntAndCommit(CookieConstants.EmergStatus, ConstantValue.EMERGSTATUS_YES);
			UserInfoSingleton.putIntAndCommit(CookieConstants.VideoStatus, ConstantValue.VIDEOSTATUS_NO);
			
			LogTool.addPlayLog("文字","开始显示","00:00:00:00","开始显示紧急消息:"+data.getTextContent());
			LogTool.addRunlog("设备控制","开始显示紧急消息");
			

			if(data.getTextContent().length()>300){
				ViewManager.getInstance().getExigentInfo().setTextSize(40f);
			}
			
			
		}catch(Exception e){
			LogUtil.e(TAG,"解析" + module_name
					+ ".xml出错 :\n", e);
		}
	}
	/**
	 * 停止紧急消息<br>
	 * 2013-12-13 下午2:20:28
	 *
	 */
	public void stopExigent(){
		
		if(!isExigent) return;
		UserInfoSingleton.putIntAndCommit(CookieConstants.EmergStatus, ConstantValue.EMERGSTATUS_NO);
		UserInfoSingleton.putIntAndCommit(CookieConstants.VideoStatus, ConstantValue.VIDEOSTATUS_YES);
		
		LogTool.addPlayLog("文字","停止显示","00:00:00:00","停止显示紧急消息");
		LogTool.addRunlog("设备控制","停止显示紧急消息");
		UserInfoSingleton.setIsExigent("1");
		////测试开始
		int count=viewGroup.getChildCount();
		for(int i=0;i<count;i++ ){
			View v=viewGroup.getChildAt(i);
			if(v instanceof MExigent){
				v.setVisibility(View.GONE);
			}else{
				v.setVisibility(View.VISIBLE);
			}
		}
		String flag1=UserInfoSingleton.getIslive();

		
		if(flag1.equals(ConstantValue.PLAY_LOCAL)){
			/**
			 * 显示本地视频
			 */
			ViewManager.getInstance().getlVideo().setVisibility(View.VISIBLE);
			ViewManager.getInstance().getVideoInfo().startPlay();
		}else{
			Intent mIntent = new Intent(RecvBase.ACTION_CMD_MAIN);
			mIntent.putExtra("cmd",RecvBase.CMD_CONTROL_PLAYSTREAM);
			//发送广播
			sendBroadcast(mIntent);
		}
//		initViewGroup();
		viewGroup.setBackgroundDrawable(bk_drawable);// 设置模板背景图片
		//新加
//		ViewManager.getInstance().changeContentView(viewGroup, moduleInfoList);
		
//		sendControlBroadcast(RecvBase.CMD_CONTROL_PLAY,null);
	    ////测试结束
		
	}
	public class PlayThread extends Thread{

		/* (non-Javadoc)
		 * @see java.lang.Thread#run()
		 */
		@Override
		public void run() {
			playLocal();
			super.run();
		}
		
	}
	/**
	 * 找到下一个播放项。
	 */
	void findNext() {
		if (iterator.hasNext()) {
			next_item = iterator.next();
		} else { // 模板列表项播完了就再播第一项。
			while (iterator.hasPrevious()) {
				iterator.previous();
			}
			next_item = iterator.next();
		}
	}

	/**
	 * 计算某个时间点的时、分、秒对应的毫秒值
	 * 
	 * @param time  时间点
	 * @return 时间的时分秒对应的毫秒值
	 */
	private int timeToMillis(Time time) {
		return time.hour * 60 * 60 * 1000 + time.minute * 60 * 1000
				+ time.second * 1000;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	 private final BroadcastReceiver serviceReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			  String action = intent.getAction();
			  short cmd=intent.getShortExtra("cmd", (short)0);
			  LogUtil.i(TAG, "action="+action+",cmd="+cmd);
			  
			  switch(cmd){
			  	case RecvBase.CMD_CONTROL_PLAY:
			  		mplayPlay();
			  		break;
				case RecvBase.CMD_CONTROL_STOP:
					mplayStopThread();
					break;
				case RecvBase.CMD_CONTROL_REPLAY:
				case RecvBase.CMD_CONTROL_PAUSEPLAY:
					ViewManager.getInstance().getVideoInfo().receiveCmdControl(cmd, null);
					
					break;
				case RecvBase.CMD_CONTROL_SOUNDON:
					UserInfoSingleton.putBooleanAndCommit(CookieConstants.GlobalAudioStatus,false);
					UserInfoSingleton.putIntAndCommit(CookieConstants.AudioStatus,ConstantValue.AUDIOSTATUS_YES);
					if(current!=0){
						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 
								current, 0);
					}
					
//					ViewManager.getInstance().getVideoInfo().receiveCmdControl(cmd, null);
					break;
				case RecvBase.CMD_CONTROL_SOUNDMUTE:
					UserInfoSingleton.putBooleanAndCommit(CookieConstants.GlobalAudioStatus,true);
					UserInfoSingleton.putIntAndCommit(CookieConstants.AudioStatus,ConstantValue.AUDIOSTATUS_NO);
					current = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC );
					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 
					0, 0);
//					ViewManager.getInstance().getVideoInfo().receiveCmdControl(cmd, null);
					break;
				case RecvBase.CMD_CONTROL_SETVOLUME:
					Bundle bundle=intent.getBundleExtra(ConstantValue.EXTRA_BUNDLE);
					/**
					 * 设置音量
					 */
					byte v=bundle.getByte("volume");
					UserInfoSingleton.putIntAndCommit(CookieConstants.AudioVolume,v);
					UserInfoSingleton.putBooleanAndCommit(CookieConstants.GlobalAudioVolume,true);
					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 
							v* max / 100, 0);
//					ViewManager.getInstance().getVideoInfo().receiveCmdControl(cmd, bundle);
					
					break;
				case RecvBase.CMD_CONTROL_PLAYSTREAM:
					/**
					 * 直播~~~~~~~~~~启动直播播放器 隐藏本地播放器
					 */
					String flag=UserInfoSingleton.getIslive();
					
					if(flag.equals(ConstantValue.PLAY_LIVE)){
						LogUtil.i(TAG, "当前处于直播状态,不要重复点击直播");
						
					}else{
						UserInfoSingleton.putIntAndCommit(CookieConstants.VideoStatus, ConstantValue.VIDEOSTATUS_YES11);
						LogUtil.i(TAG, "启动直播播放");
						UserInfoSingleton.setIslive(ConstantValue.PLAY_LIVE);
						
						Intent mIntent = new Intent(RecvBase.ACTION_CMD_MAIN);
						mIntent.putExtra("cmd",cmd);
						//发送广播
						sendBroadcast(mIntent);


					}
					
					break;
				case RecvBase.CMD_CONTROL_PLAYLOCAL:
					/**
					 * 本地~~~~~~~~~~启动本地播放器 隐藏直播播放器
					 */
					String flag1=UserInfoSingleton.getIslive();
					
					if(flag1.equals(ConstantValue.PLAY_LOCAL)){
						LogUtil.i(TAG, "当前处于本地状态,不要重复点击本地");
						
					}else{
						UserInfoSingleton.putIntAndCommit(CookieConstants.VideoStatus, ConstantValue.VIDEOSTATUS_YES);
						LogUtil.i(TAG, "启动本地播放");
						UserInfoSingleton.setIslive(ConstantValue.PLAY_LOCAL);
//						handler.post(new PlayLiveThread(false));
						Intent mIntent = new Intent(RecvBase.ACTION_CMD_MAIN);
						mIntent.putExtra("cmd",cmd);
						//发送广播
						sendBroadcast(mIntent);
					}
					
					break;
				case RecvBase.CMD_CONTROL_PLAYSTREAM_Z:
//					handler.post(new PlayLiveThread(true));
					Intent mIntent = new Intent(RecvBase.ACTION_CMD_MAIN);
					mIntent.putExtra("cmd",RecvBase.CMD_CONTROL_PLAYSTREAM);
					//发送广播
					sendBroadcast(mIntent);
					break;
				case RecvBase.CMD_CONTROL_PLAYLOCAL_L:
//					handler.post(new PlayLiveThread(false));
					Intent mIntent1 = new Intent(RecvBase.ACTION_CMD_MAIN);
					mIntent1.putExtra("cmd",RecvBase.CMD_CONTROL_PLAYLOCAL);
					//发送广播
					sendBroadcast(mIntent1);
					
					break;
				case RecvBase.CMD_CONTROL_PLAYLOCAL_1:
					/**
					 * 显示本地视频
					 */
					ViewManager.getInstance().getlVideo().setVisibility(View.VISIBLE);
					ViewManager.getInstance().getVideoInfo().startPlay();
					
					break;
				case RecvBase.CMD_CONTROL_TAKE:
					/**
					 * 节目单--切换模板
					 */
					if(null==layout_list)return;
					if(layout_list.size()>1){
						take();
					}
					
					break;
				case (short)100:
					ViewManager.getInstance().getlVideo().setVisibility(View.GONE);
					ViewManager.getInstance().getlVideo().stopPlayback();
					
					break;
				case RecvBase.CMD_TEXT_SETPROIRITY:
					PriorityTextData data=(PriorityTextData)intent.getSerializableExtra(ConstantValue.EXTRA_OBJ);
//					/**
//					 * 保存对象
//					 */
//					POPriorityText po=CopyUtils.copyFromPriorityTextData(data);
//					Map<String, Object> map=new HashMap<String, Object>();
//					map.put("textID", po.getTextID());
//					/**
//					 * textID要唯一 添加时候进行验证
//					 */
//					int result=mDbHelper.createIfNotExists(po, map);
//					
//					LogUtil.i(TAG, "添加结果：result="+result);
//					if(result==-1)return;
//					
//					int uid=data.getUid();
//					
//					if(uid==RecvBase.UID_URGENT){
						receiveMsg(data);
//					}else{
//						
//					}
					

					break;
				case RecvBase.CMD_TEXT_STOP:
					currPriorityDatas=new ArrayList<PriorityTextData>(); // 紧急消息集合;
					stopExigent();
					
					break;
				case RecvBase.CMD_FILE_SETLIST:
					/**
					 * 接收到新节目单开始播放新节目单
					 */
					stopLive();
					LogUtil.i(TAG, "接收到新节目单开始播放新节目单");
					UserInfoSingleton.setIslive(ConstantValue.PLAY_LOCAL);
					closeViewThread();
					try {
						current_layout_item=null;
						next_item=null;
						playlist_dir="";
//						sendControlBroadcast(RecvBase.CMD_CONTROL_PLAY,null);
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					
						e.printStackTrace();
					}
					down();

					break;
				default:
					ViewManager.getInstance().changeContentView(viewGroup,
							moduleInfoList);
						break;
						
				}
		}
		 
	 };
	
	 
	
	 public void sendControlBroadcast(int cmdId,Bundle bundle){
		 Intent mIntent = new Intent(RecvBase.ACTION_CMD_CONTROL);
		 mIntent.putExtra("cmd",(short)cmdId);
		 mIntent.putExtra(ConstantValue.EXTRA_BUNDLE, bundle);
		 //发送广播
		 sendBroadcast(mIntent);
	 }
	/**
	 * 关闭线程changeViewThread<br>
	 * 2013-12-5 下午2:23:31
	 *
	 */
	public void closeViewThread(){
		try{
			if(null!=changeViewThread){
				isChangeView=false;
				changeViewThread.interrupt(); //服务销毁时，线程跟着停止。
					try {
					 changeViewThread.join(3000);
				    } catch (InterruptedException e) {
				      e.printStackTrace();
				    }
				changeViewThread=null;
				
			}
			
		}catch(Exception e){
			LogUtil.e(TAG, "closeViewThread err", e);
		}
		
	}
	/**
	 * 停止直播
	 * 2014-10-30 下午2:11:51
	 *
	 */
	private void stopLive(){
		String flag1=UserInfoSingleton.getIslive();
		if(!flag1.equals(ConstantValue.PLAY_LOCAL)){
			UserInfoSingleton.setIslive(ConstantValue.PLAY_LOCAL);
			UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsRefresh, true);
			
			Intent mIntent = new Intent(RecvBase.ACTION_CMD_MAIN);
			mIntent.putExtra("cmd",RecvBase.CMD_CONTROL_PLAYLOCAL);
			//发送广播
			sendBroadcast(mIntent);
		}
	}
	
	private void stopLiveBut(){
		String flag1=UserInfoSingleton.getIslive();
		if(!flag1.equals(ConstantValue.PLAY_LOCAL)){
			
			UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsRefresh, true);
			Intent mIntent = new Intent(RecvBase.ACTION_CMD_MAIN);
			mIntent.putExtra("cmd",RecvBase.CMD_CONTROL_PLAYLOCAL);
			//发送广播
			sendBroadcast(mIntent);
		}
		
	}
	private void take(){
		stopLive();
		current_layout_item = next_item;
		findNext();
		initCurrentLayout();
	
		ViewManager.getInstance().changeContentView(viewGroup, moduleInfoList); // 更改界面
		
	}
	
	/**
	 * 根据模板文件的显示时间， 开启一个线程每隔一秒判断一次当前需解析并显示哪一个模板文件。
	 */
	private class ChangeViewThread extends Thread {
		long currentTimeMillis=0;
		Time start_time=null;
		Time current_time=null;
		@Override
		public void run() {
			
			while (isChangeView) {
				currentTimeMillis = System.currentTimeMillis();
				current_time = new Time();
				current_time.set(currentTimeMillis);
				start_time = next_item.getStart_time(); // 开始时间
				if (timeToMillis(current_time) >= timeToMillis(start_time)) { // 如果当前时间晚于或等于下一个待播放模板开始时间
					current_layout_item = next_item;
//					findNext();
//					initCurrentLayout();
//					Intent mIntent = new Intent(RecvBase.ACTION_CMD_CONTROL);
//					mIntent.putExtra("cmd", 0);
//					//发送广播
//					sendBroadcast(mIntent);
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	};

}
